<template>
  <section style="padding:10px;">
    <!--查询-->
    <el-form class="ad-form-query" :inline="true" :model="filters" @submit.native.prevent>
      <el-form-item>
        <el-input v-model="filters.label" placeholder="名称" clearable @keyup.enter.native="onGetList">
          <template #prefix>
            <i class="el-input__icon el-icon-search" />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="warning" icon="el-icon-search" @click="onGetList">查询</el-button>
      </el-form-item>
      <el-form-item v-if="checkPermission(['admin_sysdictionary_add'])">
        <el-button type="primary" icon="el-icon-plus" @click="onAdd">新增</el-button>
      </el-form-item>
      <el-form-item v-if="checkPermission(['admin_sysdictionary_delete'])">
        <my-confirm-button
          :disabled="sels.length === 0"
          :type="'delete'"
          :placement="'bottom-end'"
          :loading="deleteLoading"
          style="margin-left: 0px;"
          @click="onBatchDelete"
        >
          <template #content>
            <p>确定要批量删除吗？</p>
          </template>
          批量删除
        </my-confirm-button>
      </el-form-item>
    </el-form>

    <!--列表-->
    <el-table
      ref="multipleTable"
      v-loading="listLoading"
      row-key="id"
      border
      :data="viewTree"
      :default-expand-all="false"
      :expand-row-keys="expandRowKeys"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      :header-cell-style="{background:'#f9f9f9'}"
      highlight-current-row
      style="width: 100%;margin:10px 0;"
      @select-all="onSelectAll"
      @select="onSelect"
    >
      <el-table-column type="selection" width="50" />
      <el-table-column type="index" width="50" label="#" />
      <el-table-column prop="name" label="名称" width="180" />
      <el-table-column prop="code" label="唯一编码" width />
      <el-table-column prop="value" label="值" width />
      <el-table-column prop="sort" label="排序" width />
      <el-table-column label="操作" width="180">
        <template #default="{ $index, row }">
          <el-button v-if="checkPermission(['admin_sysdictionary_update'])" type="success" icon="el-icon-edit" @click="onEdit($index, row)">编辑</el-button>
          <my-confirm-button v-if="checkPermission(['admin_sysdictionary_delete'])" type="delete" :loading="row._loading" @click="onDelete($index, row)" />
        </template>
      </el-table-column>
    </el-table>

    <!--新增窗口-->
    <el-dialog
      title="新增"
      :visible.sync="addFormVisible"
      :close-on-click-modal="false"
      @close="onCloseAddForm"
    >
      <el-form ref="addForm" :model="addForm" label-width="80px" :rules="addFormRules" size="medium">
        <el-form-item prop="parentId" label="上级">
          <el-cascader
            :key="addFormKey"
            v-model="addForm.parentId"
            placeholder="请选择，支持搜索功能"
            :options="modules"
            :props="{ checkStrictly: true, value: 'id',label:'name' }"
            filterable
            style="width:100%;"
          />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="addForm.name" auto-complete="off" />
        </el-form-item>
        <el-form-item label="编码" prop="code">
          <el-input v-model="addForm.code" auto-complete="off" />
        </el-form-item>
        <el-form-item label="值" prop="value">
          <el-input v-model="addForm.value" auto-complete="off" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="addForm.sort" auto-complete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click.native="addFormVisible = false">取消</el-button>
          <my-confirm-button type="submit" :validate="addFormValidate" :loading="addLoading" @click="onAddSubmit" />
        </div>
      </template>
    </el-dialog>

    <!--编辑窗口-->
    <el-dialog
      title="编辑"
      :visible.sync="editFormVisible"
      :close-on-click-modal="false"
      @close="onCloseEditForm"
    >
      <el-form ref="editForm" :model="editForm" :rules="editFormRules" label-width="80px" size="medium">
        <el-form-item prop="parentId" label="所属模块">
          <el-cascader
            :key="editFormKey"
            v-model="editForm.parentId"
            placeholder="请选择，支持搜索功能"
            :options="modules"
            :props="{ checkStrictly: true, value: 'id',label:'name' }"
            filterable
            style="width:100%;"
          />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="editForm.name" auto-complete="off" />
        </el-form-item>
        <el-form-item label="编码" prop="code">
          <el-input v-model="editForm.code" auto-complete="off" />
        </el-form-item>
        <el-form-item label="值" prop="value">
          <el-input v-model="editForm.value" auto-complete="off" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="editForm.sort" auto-complete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click.native="editFormVisible = false">取消</el-button>
          <my-confirm-button type="submit" :validate="editFormValidate" :loading="editLoading" @click="onEditSubmit" />
        </div>
      </template>
    </el-dialog>
  </section>
</template>

<script>
import { treeToList, listToTree, getTreeParents } from '@/utils'
import {
  getDicList, addDic, removeDic, getDic, editDic
} from '@/api/admin/dictionary'
import MyConfirmButton from '@/components/my-confirm-button'

export default {
  name: 'Dictionary',
  components: {
    MyConfirmButton
  },
  data() {
    return {
      filters: {
        label: ''
      },
      viewTree: [],
      expandRowKeys: [],
      listLoading: false,
      sels: [], // 列表选中列

      addDialogFormVisible: false,
      editFormVisible: false, // 编辑界面是否显示
      editLoading: false,
      editFormRules: {
        parentId: [{ required: true, message: '请选择上级节点', trigger: 'change' }],
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        value: [{ required: true, message: '请输入值', trigger: 'blur' }],
        sort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
        code: [{ required: true, message: '请输入编码', trigger: 'blur' }]
      },
      // 编辑界面数据
      editForm: {
        id: 0,
        parentId: '0',
        code: '',
        value: '',
        sort: 0,
        name: ''
      },
      editFormKey: 1,

      addFormVisible: false, // 新增界面是否显示
      addLoading: false,
      addFormRules: {
        parentId: [{ required: true, message: '请选择上级节点', trigger: 'change' }],
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        value: [{ required: true, message: '请输入值', trigger: 'blur' }],
        sort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
        code: [{ required: true, message: '请输入编码', trigger: 'blur' }]
      },
      // 新增界面数据
      addForm: {
        parentId: '0',
        name: '',
        code: '',
        value: '',
        sort: 0
      },
      addFormKey: 1,
      modules: [],
      deleteLoading: false
    }
  },
  mounted() {
    this.onGetList()
  },
  methods: {

    // 获取列表
    async onGetList() {
      const para = {
        Name: this.filters.label
      }
      this.listLoading = true
      const res = await getDicList(para)
      this.listLoading = false

      if (!res?.success) {
        return
      }
      const list = _.cloneDeep(res.data)
      const keys = list.filter(l => l.parentId === 0).map(l => l.id + '')
      this.expandRowKeys = keys
      this.modules = listToTree(_.cloneDeep(list), {
        id: '0',
        parentId: '',
        name: '根节点'
      })
      list.forEach(l => {
        l._loading = false
      })
      const tree = listToTree(list)
      this.sels = []
      this.viewTree = tree
    },
    // 显示编辑界面
    async onEdit(index, row) {
      const loading = this.$loading()
      const res = await getDic({ id: row.id })
      loading.close()
      if (res && res.success) {
        const parents = getTreeParents(this.viewTree, row.id)
        const parentIds = parents.map(p => p.id)
        const data = res.data
        data.parentIds = parentIds
        this.editForm = data
        this.editFormVisible = true
        ++this.editFormKey
      }
    },
    onCloseEditForm() {
      this.$refs.editForm.resetFields()
      ++this.editFormKey
    },
    // 显示新增界面
    onAdd() {
      this.addFormVisible = true
    },
    onCloseAddForm() {
      this.$refs.addForm.resetFields()
      ++this.addFormKey
    },
    // 编辑
    editFormValidate: function() {
      let isValid = false
      this.$refs.editForm.validate(valid => {
        isValid = valid
      })
      return isValid
    },
    async onEditSubmit() {
      this.editLoading = true
      const para = _.cloneDeep(this.editForm)
      if (Array.isArray(para.parentId)) {
        para.parentId = para.parentId.pop()
      }
      if (para.id === para.parentId) {
        this.$message({
          message: '上级不能是自己！',
          type: 'error'
        })
        this.editLoading = false
        return
      }

      const res = await editDic(para)
      this.editLoading = false

      if (!res?.success) {
        return
      }

      this.$message({
        message: this.$t('admin.updateOk'),
        type: 'success'
      })
      this.$refs['editForm'].resetFields()
      this.editFormVisible = false
      this.onGetList()
    },
    // 新增
    addFormValidate: function() {
      let isValid = false
      this.$refs.addForm.validate(valid => {
        isValid = valid
      })
      return isValid
    },
    async onAddSubmit() {
      this.addLoading = true
      const para = _.cloneDeep(this.addForm)
      para.parentId = para.parentId.pop()
      const res = await addDic(para)
      this.addLoading = false

      if (!res?.success) {
        return
      }
      this.$message({
        message: this.$t('admin.addOk'),
        type: 'success'
      })
      this.$refs['addForm'].resetFields()
      this.addFormVisible = false
      this.onGetList()
    },
    // 删除
    async onDelete(index, row) {
      row._loading = true
      const para = { ids: [] }
      para.ids.push(row.id)
      const res = await removeDic(para.ids)

      row._loading = false

      if (!res?.success) {
        return
      }
      this.$message({
        message: this.$t('admin.deleteOk'),
        type: 'success'
      })
      this.onGetList()
    },
    // 批量删除
    async onBatchDelete() {
      const para = { ids: [] }
      para.ids = this.sels.map(s => {
        return s.id
      })

      this.deleteLoading = true
      const res = await removeDic(para.ids)
      this.deleteLoading = false

      if (!res?.success) {
        return
      }

      this.$message({
        message: this.$t('admin.batchDeleteOk'),
        type: 'success'
      })

      this.onGetList()
    },
    onSelectAll: function(selection) {
      const selections = treeToList(selection)
      const rows = treeToList(this.viewTree)
      const checked = selections.length === rows.length
      rows.forEach(row => {
        this.$refs.multipleTable.toggleRowSelection(row, checked)
      })
      this.sels = this.$refs.multipleTable.selection
    },
    onSelect: function(selection, row) {
      const checked = selection.some(s => s.id === row.id)
      if (row.children && row.children.length > 0) {
        const rows = treeToList(row.children)
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row, checked)
        })
      }
      this.sels = this.$refs.multipleTable.selection
    }
  }
}
</script>
